import {defineStore} from "pinia";
import Cookies from "js-cookie";
import {ref} from "vue";

const remember = ref(false)
const cookiesStorage = {
    setItem(key, state) {
        console.log(`setItem ${key} -- ${state}`);
        //Json 字符串对象转换成JS对象
        let myState = JSON.parse(state);
        if (remember.value) {
            return Cookies.set(key, myState.token, {expires: 7})
        } else {
            return Cookies.set(key, myState.token)
        }
    },
    getItem(key) {
        return JSON.stringify({
            token: Cookies.get(key)
        });
    }
}

export const useTokenStore = defineStore("token", {
    //存数据的地方
    state() {
        return {
            token: ''
        }
    },
    //actions里放一个一个方法
    actions: {
        setToken(newToken, rem) {
            this.token = newToken
            remember.value = rem
        },
        removeToken() {
            this.token = ''
        }
    },
    persist: {
        enabled: true,  //开启缓存，默认会存储在本地localstorage
        storage: cookiesStorage,
    }
})